import React, {Component} from 'react';
import {
    Text, TextInput, TouchableOpacity, View, Alert, StyleSheet, AsyncStorage, FlatList, Image,
    ScrollView
} from 'react-native';
import Spinner from 'react-native-loading-spinner-overlay';
import Toast from '@remobile/react-native-toast';
import {BasicStyle} from "../../../style/BasicStyle";
import FetchUtils from './../../utils/FetchUtils';
import utils from './../../utils/utils';

export default class MyOrderList extends Component {
    static navigationOptions = ({navigation, screenProps}) => ({
        headerTitle: "我的订单",
        headerStyle: {
            backgroundColor: '#F6F6F6',
        },
        headerTitleStyle: {
            alignSelf: 'center',
            fontSize: utils.setSpText(17),
        },
        headerRight: <TouchableOpacity/>
    });

    constructor() {
        super();
        this.state = {
            datas: '',
            list: [],
            size: 5,
            page: 0,
            lastStatus: '',
            loadingStatus: false,
        }
    }

    componentDidMount() {
        AsyncStorage.getItem("XToken").then((xToken) => {
            if (!this.state.lastStatus) {
                let params = {
                    page: this.state.page,
                    size: this.state.size,
                };
                FetchUtils.getWithHeader(utils.apiUrl + '/order/list', xToken, params, (res) => {
                    if (res.code === 200) {
                        console.log(res.apiData);
                        this.setState({
                            datas: res.apiData,
                            lastStatus: res.apiData.last
                        })
                    } else {
                        Toast.showShortTop("请求错误：" + res.apiData);
                    }
                })
            }
        })
    }

    render() {
        return (
            <View style={BasicStyle.containerView}>
                <Spinner visible={this.state.loadingStatus} textContent={""} textStyle={{color: '#FFF'}}/>
                <ScrollView
                    showsVerticalScrollIndicator={false}
                    showsHorizontalScrollIndicator={false}
                    removeClippedSubviews={false}
                    onMomentumScrollEnd={this._onScroll.bind(this)}
                >
                    {this.state.datas === '' ? null : this._makeList(this.state.datas.content)}
                </ScrollView>
            </View>
        )
    }

    /*scrollView滑动方法*/
    _onScroll(event) {
        let y = event.nativeEvent.contentOffset.y;//滑动距离
        let height = event.nativeEvent.layoutMeasurement.height;//scrollView高度
        let contentHeight = event.nativeEvent.contentSize.height;//scrollView contentSize高度
        if (y + height >= contentHeight) {
            if (!this.state.lastStatus) {
                this.setState({
                    loadingStatus: true
                });
                AsyncStorage.getItem("XToken").then((xToken) => {
                    let params = {
                        page: this.state.page + 1,
                        size: this.state.size,
                    };
                    FetchUtils.getWithHeader(utils.apiUrl + '/order/list', xToken, params, (res) => {
                        if (res.code === 200) {
                            let newDatas = {
                                content: this.state.datas.content.concat(res.apiData.content),
                                totalElements: this.state.datas.totalElements,
                                size: this.state.datas.size,
                                number: this.state.datas.number,
                                totalPages: this.state.datas.totalPages,
                                last: this.state.datas.last,
                            };
                            this.setState({
                                datas: newDatas,
                                lastStatus: res.apiData.last,
                                page: res.apiData.number,
                                size: res.apiData.size,
                                loadingStatus: false,
                            });
                            console.log(this.state.datas)
                        } else {
                            Toast.showShortTop("请求错误：" + res.apiData);
                        }
                    })
                })
            }
        } else {
            this.setState({loadingStatus: false})
        }
    }

    /*生成列表*/
    _makeList = (datas) => {
        let datasList = datas.map((contentItem, index) => {
            return <View key={index} style={{marginBottom: utils.autoheight(21)}}>
                <View style={{
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    height: utils.autoheight(40),
                    alignItems: 'center',
                    paddingLeft: utils.autoWidth(12),
                    paddingRight: utils.autoWidth(12),
                    backgroundColor: '#FFF'
                }}>
                    <TouchableOpacity style={{flex: 1}} onPress={() => {
                        let {navigate} = this.props.navigation;
                        navigate('MyOrderDedailNav', {orderId: contentItem.orderId});
                    }}><Text
                        style={BasicStyle.commonFontLittleText}>订单号：{contentItem.orderId}</Text></TouchableOpacity>
                    <TouchableOpacity
                        style={{flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', flex: 1}}
                        onPress={() => {
                            let {navigate} = this.props.navigation;
                            if (contentItem.orderStatus === 0) {
                                navigate('ShopOrderPayNav', {orderId: contentItem.orderId});
                            } else {
                                navigate('MyOrderDedailNav');
                            }
                        }}>
                        <Text style={BasicStyle.commonFontLittleText}>
                            {contentItem.orderStatus === 0 ? '未支付' : ''}
                            {contentItem.orderStatus === 11 ? '已支付' : ''}
                            {contentItem.orderStatus === 22 ? '已发货' : ''}
                            {contentItem.orderStatus === 33 ? '已收货' : ''}
                            {contentItem.orderStatus === 44 ? '已完成' : ''}
                        </Text>
                        <Image style={[BasicStyle.rightPointImg, {marginLeft: utils.autoWidth(6)}]}
                               source={require('./../../../img/rightpoint.png')}/>
                    </TouchableOpacity>
                </View>
                {this._makeProductList(contentItem.orderProductModelList, contentItem.shopCarNum, contentItem.shopCarSumPrice)}

                <View style={{
                    height: utils.autoheight(40),
                    backgroundColor: '#FFF',
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                }}>
                    <View style={{marginLeft: utils.autoWidth(12)}}>
                        <Text style={BasicStyle.commonFontLittleText}>共 {contentItem.shopCarNum} 件</Text>
                    </View>

                    <View style={{flexDirection: 'row', alignItems: 'center', marginRight: utils.autoWidth(30)}}>
                        <Text style={[BasicStyle.commonFontLittleText,]}>总计</Text>
                        <Text
                            style={{fontSize: utils.setSpText(21), color: '#000'}}>￥{utils.toDecimal2(contentItem.shopCarSumPrice)}</Text>
                    </View>

                </View>

            </View>
        });
        return datasList;

    };

    /*生成商品列表*/
    _makeProductList = (productList) => {
        let proListView = productList.map((productItem, index) => {
            return <TouchableOpacity key={index} style={{
                height: utils.autoheight(100),
                marginTop: utils.autoheight(0.5),
                marginBottom: utils.autoheight(0.5),
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                backgroundColor: '#FFF'
            }} onPress={() => {
                let {navigate} = this.props.navigation;
                navigate('ShopDetailNav', {productId: productItem.productId})
            }
            }>
                <Image
                    style={{
                        height: utils.autoheight(75.2),
                        width: utils.autoWidth(70),
                        marginLeft: utils.autoWidth(14),
                        marginRight: utils.autoWidth(10)
                    }}
                    source={{uri: utils.qiniuUrl + productItem.mainImg + utils.qiniu200Url}}/>
                <View style={{flex: 1}}>
                    <Text style={BasicStyle.commonFontText}>{productItem.productName}</Text>
                    <Text
                        style={BasicStyle.commonFontLittleText}>“{productItem.productColor}”，“{productItem.productSize}”</Text>

                    <View style={{
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        paddingRight: utils.autoWidth(33)
                    }}>
                        <Text style={BasicStyle.commonFontText}>￥{utils.toDecimal2(productItem.nowPrice)}</Text>
                        <Text style={BasicStyle.commonFontText}>X {productItem.productNum}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        });

        return proListView;
    }

}

